package com.tinysand.advert.index;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.PriorityOrdered;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created By TINY
 * Create Time 2020/2/27
 **/
@Component
public class DataTable
        implements ApplicationContextAware, PriorityOrdered {

    private static ApplicationContext applicationContext;

    // 保存所有数据索引对象
    private static final Map<Class, Object> dataTableMap =
            new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(
            @NonNull ApplicationContext applicationContext)
            throws BeansException {
        DataTable.applicationContext = applicationContext;
    }

    @Override
    public int getOrder() {
        return PriorityOrdered.HIGHEST_PRECEDENCE;
    }

    /* 根据类型获取数据索引类 */
    @SuppressWarnings("unchecked")
    public static <T> T of(Class<T> clazz) {
        T instance = (T) dataTableMap.get(clazz);

        if (null != instance) { return instance; }

        dataTableMap.put(clazz, getBean(clazz));
        return (T) dataTableMap.get(clazz);
    }

    @SuppressWarnings("unchecked")
    private static <T> T getBean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }

    @SuppressWarnings("unchecked")
    private static <T> T getBean(Class clazz) {
        return (T) applicationContext.getBean(clazz);
    }
}
